package compile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author hewenhui
 * @see <a href="hetp://www.codingmaster.com> java </a>
 */
public class CommandUtil {
    public static int run(String cmd, String stdout, String stderr) {
        try {
            // 0、创建子进程
           Process process = Runtime.getRuntime().exec(cmd);
            // 1、将子进程的标准输出写入指定文件
            if (stdout != null) {
                InputStream stdoutFrom = process.getInputStream();
                FileOutputStream stdoutTo = new FileOutputStream(stdout);
                int ch;
                while ((ch = stdoutFrom.read()) != -1) {
                    stdoutTo.write(ch);
                }
                stdoutFrom.close();
                stdoutTo.close();
            }
            // 2、将子进程的标准错误写入指定文件
            if (stderr != null) {
                InputStream stderrFrom = process.getErrorStream();
                FileOutputStream stderrTo =new FileOutputStream(stderr);
                int ch;
                while ((ch = stderrFrom.read()) != -1) {
                    stderrTo.write(ch);
                }
                stderrFrom.close();
                stderrTo.close();
            }
            // 3、父进程等待子进程结束，并返回子进程的exitCode
            return process.waitFor();
        } catch (IOException | InterruptedException e) {
            // 4、异常处理
            e.printStackTrace();
        }
        // 5、返回1表示run()执行目的失败
        return 1;
    }
    // 测试
    public static void main(String[] args) {
//        run("javac Solution.java","stdout1.txt","stderr1.txt");
        run("java Solution","stdout2.txt","stderr2.txt");
    }
}

